package com.ssetest;

import io.minio.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.CompletableFuture;

@RestController
public class SseController {

    @Autowired
    private SseService service;

    @RequestMapping("/emitter")
    public SseEmitter sse(@RequestBody String inputParameter, HttpServletResponse response) {
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        SseEmitter emitter = new SseEmitter();

        // Simulate asynchronous data retrieval from the database
        new Thread(() -> {
            try {
                // Query the database based on the input parameter and send data in batches
                for (int i = 0; i < 10; i++) {
                    String data = "Data batch " + i + " for parameter: " + inputParameter;
                    emitter.send(data);
                    Thread.sleep(1000); // Simulate delay between batches
                }

                emitter.complete(); // Complete the SSE connection
            } catch (Exception e) {
                emitter.completeWithError(e); // Handle errors
            }
        }).start();

        return emitter;
    }

    @GetMapping(value = "test/{clientId}", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter test(@PathVariable("clientId") String clientId) {
        final SseEmitter emitter = service.getConn(clientId);
        CompletableFuture.runAsync(() -> {
            try {
                service.send(clientId);
            } catch (Exception e) {
                throw new RuntimeException("推送数据异常");
            }
        });

        return emitter;
    }

    @GetMapping("closeConn/{clientId}")
    public String closeConn(@PathVariable("clientId")  String clientId) {
        service.closeConn(clientId);
        return "连接已关闭";
    }
}
